<template>
    <div class="contact-page">

        <!-- 过滤好友、群聊信息 -->
        <div id="filter-btns" class="flex items-center">
            <n-input v-model:value="filterFriendInfo" :minlength="1" :maxlength="10" style="width: 200px;" />
            <n-popover trigger="click" placement="right">
                <template #trigger>
                    <n-button size="medium" style="width: 40px;height: 37px;" color="#8a2be2" ghost>
                        <template #icon>
                            <img src="https://img.icons8.com/?size=100&id=62888&format=png&color=000000" alt="">
                        </template>
                    </n-button>
                </template>
                <div class="more-menus">
                    <!-- 创建群聊 -->
                    <div id="create-btns" @click="handleHeaderMenuClick('create-groups')">
                        <span>创建群聊</span>
                    </div>
                    <!-- 添加好友 -->
                    <div id="add-btns" @click="handleHeaderMenuClick('user-recommend-and-search-friend')">
                        <span>添加朋友</span>
                    </div>
                </div>
            </n-popover>
        </div>

        <!-- 展示好友信息、群聊信息 -->
        <div id="show-friends-info-list">
            <!-- <el-input v-model="searchFriend" placeholder="输入好友姓名" clearable>
                <template #prefix>
                    <el-icon>
                        <User />
                    </el-icon> </template>?
<template #append>
                    <el-button @click="showAddGroupChatStatus = true">+</el-button>
                </template>
</el-input> -->
            <!-- <n-input v-model:value="searchFriend" placeholder="好友信息" /> -->
            <!-- 好友列表 -->
            <!-- flex flex-column flex-wrap items-center justify-around -->

            <!-- 最终聊天列表 -->
            <div class="bubbles-chat-list">
                <n-scrollbar>
                    <div class="list-items flex items-center justify-evenly"
                        v-for="(listItem, listItemIndex) in computedMergeList" :key="listItemIndex"
                        @click="clickChat(listItem, listItem.type)">
                        <div id="avatar">
                            <n-avatar :src="listItem.avatar" size="large" />
                        </div>
                        <!-- 基本信息 -->
                        <div class="list-basic-info">
                            <span>{{ getFriendRemarks(listItem) || listItem.displayName }}</span>
                            <p>最近一条消息....暂未完成</p>
                        </div>
                    </div>
                </n-scrollbar>
            </div>
            <n-tabs type="segment" animated style="position: absolute;width: 238px;margin-top: 1px;" size="small"><n-tab
                    name="联系人" @click="showManagerModal = true"></n-tab></n-tabs>
            <!-- <el-tabs v-model="currentActiveTab" type="border-card" @tab-click="handleTabClick">
                <el-tab-pane label="用户" name="userManager">
                    <template #label>
                        <el-icon>
                            <User />
                        </el-icon>
                    </template> -->
            <!-- 在这里使用element-plus构建上下滑动的菜单 -->
            <!-- <el-scrollbar>
                        <FoldInfo :user-friend-list="storageUserFriendList" />
                    </el-scrollbar>
                </el-tab-pane>
            </el-tabs> -->
        </div>
    </div>


    <!-- dialog：显示好友信息和添加群聊信息 -->
    <n-modal v-model:show="showManagerModal">
        <n-card size="huge" role="dialog" aria-modal="true" :bordered="false"
            style="position: fixed;width: 600px;height: 450px;left: 320px;">
            <template #header-extra>
                奥！
            </template>
            <n-tabs default-value="divide-into-groups" v-model:value="activeNTab">
                <n-tab-pane name="divide-into-groups" tab="分组">
                    <!-- <n-menu :options="props.groupedMenus" v-model:value="selectGroupKey"
                        @update:value="handleGroupSelect" /> -->
                    <!-- 在这里封装一个组件 -->
                    <n-scrollbar style="max-height: 360px;">
                        <div id="dropdown-friend-menus">
                            <ul>
                                <li v-for="item in props.groupedMenus" :key="item.value" class="menu-item"
                                    @click="toggleFriendMenu(item)">
                                    <!-- 箭头标志 -->
                                    <div>{{ item.label }}</div>
                                    <!-- 二级菜单 -->
                                    <div id="second-friend-menus">
                                        <ul v-if="item.expanded && item.children?.length! > 0" class="sub-menu">
                                            <li v-for="(child, childIndex) in item.children" :key="childIndex"
                                                class="sub-menu-item">
                                                <div id="friend-basic-info"> <!--      可以考虑在这里添加一个拖拽分组（等同于二次分组了）   -->
                                                    <n-avatar :src="child.avatar" class="friend-avatar" />
                                                    <span class="nickname">{{ child.label }}</span>
                                                    <!-- 操作按钮                                                    暂时不添加了，不然弄的太复杂了   -->
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </n-scrollbar>
                </n-tab-pane>
                <n-tab-pane name="user-recommend-and-search-friend" tab="添加朋友">
                    <n-scrollbar style="height: 357.4px;">
                        <div id="refer-friends" class="flex flex-wrap">
                            <div id="refer-items" v-for="(referItem, referItemIndex) in friend_store.recommendFriends"
                                :key="referItemIndex" @click="onContextMenu($event, websocket as WebSocket, referItem)">
                                <div id="info" class="flex items-center justify-evenly">
                                    <div id="avatar">
                                        <img :src="referItem.avatar" alt="" />
                                    </div>
                                    <div id="basic-info">
                                        <p>{{ referItem.username }}</p>
                                        <p v-if="referItem.area">{{ referItem.area }}</p>
                                        <p v-else>未知星球</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </n-scrollbar>
                </n-tab-pane>
                <n-tab-pane name="verify-information" tab="验证信息">
                    <template #tab>
                        验证信息
                        <n-badge :value="friend_store.storageFriendRequestList.length" color="red"
                            :offset="verifyBadge"></n-badge>
                    </template>
                    <div id="request-factory" v-if="friend_store.storageFriendRequestList.length > 0">
                        <n-scrollbar>
                            <div id="request-items"
                                v-for="(requestItem, requestItemIndex) in friend_store.storageFriendRequestList"
                                :key="requestItemIndex">
                                <div id="request-content" class="flex items-center justify-between"
                                    @click="console.log(requestItem)">
                                    <div id="request-avatar">
                                        <n-avatar :src="requestItem.friendAvatar" size="large" />
                                    </div>
                                    <div id="header-info" class="flex flex-col itemws-center justify-evenly">
                                        <span>{{ requestItem.username }}</span>
                                        <!-- <span>{{ requestItem.message }}</span> -->
                                        <span>{{ requestItem.requestId }}</span>
                                    </div>
                                    <div id="footer-btns">
                                        <!-- @click="acceptFriendRequest(requestItem.fromUserId)" -->
                                        <!-- <n-button type="info" @click="acceptFriendRequest(requestItem)">✔</n-button> -->
                                        <n-button
                                            @click="acceptFriendRequest(websocket as WebSocket, requestItem)">✔</n-button>
                                    </div>
                                </div>
                            </div>
                        </n-scrollbar>
                    </div>
                    <n-empty description="还没有好友请求信息哦" v-else></n-empty>
                </n-tab-pane>
                <n-tab-pane name="create-groups" tab="创建群聊">
                    <div id="add-group-dialog-info">
                        <!-- 显示创建群聊可以配置的信息 -->
                        <div class="chat-group-info flex flex-wrap items-center justify-evenly">
                            <!-- 群聊名称 -->
                            <div id="group-name">
                                <label for="name">
                                    <span>群名：</span>
                                </label>
                                <el-input id="name" v-model="pullGroupInfo.group_name" placeholder="输入群名"
                                    clearable></el-input>
                            </div>
                            <!-- 群聊类型 -->
                            <div id="group-type">
                                <label for="type">
                                    <span>群类型：</span>
                                </label>
                                <el-tree-select v-model="pullGroupInfo.group_type" :data="groupTypes" :props="{
                                    label: 'label',
                                    value: 'url',
                                    children: 'subTypes',
                                }" style="width: 200px" clearable />
                            </div>
                        </div>
                        <n-transfer v-model:value="groupMemberIds" :options="transferData"
                            :render-target-label="renderLabel">
                        </n-transfer>
                        <!-- 最后的操作按钮 -->
                        <div id="operate-btns" class="flex items-center justify-around">
                            <el-button type="primary" plain @click="sendCreateGroup(websocket as WebSocket, 'pull')">pull
                                group</el-button>
                            <el-button type="primary" plain
                                @click="sendCreateGroup(websocket as WebSocket, 'clear')">重置信息</el-button>
                        </div>
                    </div>
                </n-tab-pane>
            </n-tabs>
        </n-card>
    </n-modal>

</template>

<script setup lang="ts">
import { onMounted, ref, defineEmits, watchEffect, h, PropType, computed, defineComponent, onUnmounted } from "vue";
import { getRequestInfo, groupMemberIds } from "@components/General/Contact/contact";
import { connectWebSocket } from "@utils/webSocketService";
import { onContextMenu } from "@utils/contextMenu";
import type { UserFriendInfo, FriendMenuList, ChatList } from "@/types/types";
import {
    showAddGroupChatStatus, pullGroupInfo, infoValue, groupTypes, pullGroupChats, getFriendInfo
} from "@components/General/Contact/contact";
import { ElMessage } from "element-plus";
import { friendStore } from "@store/friendStore";
import { userStore } from "@store/userStore";
import { getChatList } from "@/utils/axiosApi";
import { acceptFriendRequest, sendCreateGroup } from "@/utils/websocketMessage/sendMessage";
import { NAvatar, TransferOption, TransferRenderTargetLabel } from "naive-ui";



const friend_store = friendStore();

let websocket = ref<WebSocket | null>(connectWebSocket());

const emits = defineEmits(["child-click", "dispose-menu", "toggleFriendMenu"]);

const props = defineProps({
    groupMenus: {
        type: Array,
        required: true
    },
    groupedMenus: {
        type: Array as PropType<FriendMenuList[]>,
        required: true
    }
})



// 过滤好友、群聊信息
const filterFriendInfo = ref<string>("");

function clickChat(data: any, type?: string) {
    const chatType = type === 'private-chat' ? 'userChat' : 'groupChat';
    emits("child-click", data, chatType);
}

const toggleFriendMenu = (item: FriendMenuList): void => {
    // 这里需要做优化，不能直接在子组件中修改父组件的原有数据
    item.expanded = !item.expanded;
    emits('toggleFriendMenu', item);
}

// 处理点击头部菜单事件
function handleHeaderMenuClick(menuType: string) {
    activeNTab.value = menuType;
    showManagerModal.value = !showManagerModal.value;
}

// 自定义badge的位置偏移
const verifyBadge = [10, -7] as const;

// 避免使用更明确的信息类型来定义这个变量，所以采用对象形式构建变量参数
const transferData = ref<{ key: string; label: string; avatar: string; value: string; }[]>([]);
// 初始化transfer信息       注意：这个数据主要是peihen-transfer组件使用的，在组件中options属性是一个数组，所以这里需要明确定义需要返回的数据
const generateData = (): { key: string; label: string; avatar: string; value: string; }[] => {
    // 如果storageUserFriendList不存在，直接返回空数组并提示
    if (!friend_store.storageUserFriendList) {
        ElMessage.warning("未知的数据！");
        return [];
    }

    // 使用map方法遍历storageUserFriendList，直接生成Option数组
    return friend_store.storageUserFriendList.map((item, index) => {
        const friend = item.friendDetails;
        // 检查好友信息是否完整
        if (friend && friend.username) {
            // 如果信息完整，返回对应的Option对象
            // 如果信息完整，返回对应的Option对象
            return {
                key: `${friend.uu_id}`, // 使用uu_id作为key
                label: `${friend.username}`, // 使用用户名作为label
                avatar: `${friend.avatar}`, // 使用头像URL作为avatar
                value: `${friend.uu_id}`, // 使用uu_id作为value
            };
        } else {
            // 如果信息不完整，打印警告信息
            // ElMessage.warning(`用户信息不完整，索引为 ${index}`);
            // 返回undefined，后续通过filter过滤掉
            return undefined;
        }
    }).filter(item => item !== undefined); // 过滤掉不完整的好友信息
};

const message = {
    type: "chat",
    content: "Hello, world!"
};

// 自定义n-transfer右侧渲染区域内容         这里尝试过多种方式，其实就是处理好n-transfer标签的o p
const renderLabel: TransferRenderTargetLabel = ({ option }) => {
    // return h('div', { style: { display: 'flex', alignItems: 'center' } }, [
    //     h('img', {
    //         src: option.avatar,
    //         alt: 'Avatar',
    //         style: { borderRadius: '50%', width: '30px', height: '30px', marginRight: '5px' }
    //     })
    // ]),
    //     h('div', { style: { marginLeft: '5px' } }, option.label)
    return h('div', { style: { display: 'flex', margin: '6px 0' } }, {
        default: () => [
            h(NAvatar, {
                round: true,
                src: option.avatar as string,
                size: 'small'
            }),
            h('div', { style: { display: 'flex', marginLeft: '6px', alignSelf: 'center' } }, { default: () => option.label })
        ]
    })
}



// 控制展示管理面板的变量
const showManagerModal = ref<boolean>(false);

// 存储n-tabs中的激活菜单
const activeNTab = ref<string>("divide-into-groups");

// 计算属性：合并列表处理
const computedMergeList = computed(() => {
    return friend_store.mergeList.map((listItem: ChatList) => {
        let avatar: string | undefined;
        let displayName: string;
        let friendId: string;

        if (listItem.type === 'group-chat') {
            avatar = listItem.groupAvatar;
            displayName = listItem.group_name;
            friendId = listItem.group_id;
        } else if (listItem.type === 'private-chat') {
            avatar = listItem.friendAvatar;
            displayName = listItem.friendName;
            friendId = listItem.friendId;
        } else {
            avatar = undefined;
            displayName = "";
            friendId = "";
        };
        return {
            ...listItem,
            avatar, displayName, friendId
        }
    })
})

// 通过计算属性获得好友备注信息
const getFriendRemarks = (listItem: ChatList): string | undefined => {
    if (!listItem) return undefined;
    if (listItem.type === 'private-chat') {
        const friend = friend_store.storageUserFriendList.find(
            (friend: UserFriendInfo) => friend.friendDetails.uu_id === listItem.friendId
        );
        return friend?.remark;
    }
}


// 使用watchEffect监听多个值的内容变化
watchEffect(() => {
    if (friend_store.storageUserFriendList.length > 0) {
        transferData.value = generateData();
    }
});

// 处理收到消息的事件
const handleMessage = (message: any) => {
    console.log('Received message:', message);
    // 处理接收到的消息
};

onMounted(async (): Promise<void> => {
    // 链接Stomp
    // connectionStompSockJS();
    getRequestInfo();
    // 获取用户好友列表
    getFriendInfo();
    // 获取好友列表
    await getChatList();
    // stompClient.value = connectionWebSocketStomp();
    // 链接socketjs（websocket的stomp协议）
    // initWebSocket(userStore().userInfo.token, handleMessage)
});

// onUnmounted( () : void => {
//     disconnectStomp();
// })
</script>

<style scoped lang="scss">
@import url(".//contact.scss");

.show-user-info-popoer {
    width: 150px;
    height: auto;
    background-color: wheat;

    .nickname,
    .area,
    .remark,
    .typeOfFriendShips,
    .group-info {
        height: 30px;
        border: 1px solid red;
    }
}

.more-menus {
    line-height: 30px;

    #create-btns,
    #add-btns {
        cursor: pointer;
        height: 30px;
        transition: background-color 0.3s ease-in-out;

        &:hover {
            background-color: rgba(0, 0, 0, 0.1);
        }
    }
}
</style>
